import { List } from 'antd';
import { Key, ReactNode } from 'react';

interface MultipleSelectListProps<T, K = Key> {
  items: T[];
  selectedKeys?: K[];
  onSelect: (keys: K[]) => void;
  getKey: (item: T) => K;
  renderItem: (item: T) => ReactNode;
  maxItemsToSelect?: number;
}

export function MultipleSelectList<T, K = Key>({
  items,
  selectedKeys = [],
  onSelect,
  getKey,
  renderItem,
  maxItemsToSelect,
}: MultipleSelectListProps<T, K>) {
  const handleItemClick = (key: K) => {
    const index = selectedKeys.indexOf(key);
    let newSelectedKeys: K[];
    if (index > -1) {
      newSelectedKeys = selectedKeys.filter((k) => k !== key);
    } else {
      if (
        typeof maxItemsToSelect === 'number' &&
        selectedKeys.length >= maxItemsToSelect
      ) {
        // Do not select more if max reached
        return;
      }
      newSelectedKeys = [...selectedKeys, key];
    }
    onSelect(newSelectedKeys);
  };

  return (
    <div className='w-[180px] h-[210px] overflow-auto border border-gray-300'>
      <List
        className='min-h-[210px] select-none'
        dataSource={items}
        size='small'
        renderItem={(item) => {
          const key = getKey(item);
          const isSelected = selectedKeys.includes(key);
          return (
            <List.Item
              className={
                isSelected
                  ? 'bg-[#f2f2ff] hover:!bg-[#e8e8f8]'
                  : 'hover:bg-[#fbfbfb]'
              }
              onClick={() => handleItemClick(key)}
            >
              {renderItem(item)}
            </List.Item>
          );
        }}
      />
    </div>
  );
}
